package com.google.code.coma.gui.dialog;

import com.google.code.coma.gui.worker.WorkerManager;
import com.google.code.coma.worker.Worker;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.util.Map;

/**
 * @author Dominik Strasser, dominikstr@gmail.com
 */
public class WorkersDialog extends Stage {
	private GridPane grid;

	public WorkersDialog() {
		super();
		initModality(Modality.APPLICATION_MODAL);
		initStyle(StageStyle.UTILITY);
		setTitle("Worker Overview");
		setWidth(720);
		setHeight(300);

		grid = new GridPane();
		grid.setPadding(new Insets(10, 10, 10, 10));
		grid.setVgap(5);
		grid.setHgap(5);
		grid.setStyle("-fx-background-color: DAE6F3");

		updateWorkers();

		Scene scene = new Scene(grid);
		setScene(scene);
	}

	private void updateWorkers() {
		grid.getChildren().clear();
		grid.add(createHeadlineLabel("WORKER ID"), 0, 0);
		grid.add(createHeadlineLabel("CLASS"), 1, 0);
		grid.add(createHeadlineLabel("STATE"), 2, 0);
		grid.add(createHeadlineLabel("ACTIONS"), 3, 0);
		Map<String, Worker> workers = WorkerManager.getWorkers();

		int rows = 1;
		for (String s : workers.keySet()) {
			grid.add(new Label(s), 0, rows);
			final Worker worker = workers.get(s);
			grid.add(new Label(worker.getClass().getName()), 1, rows);
			grid.add(new Label(worker.isActive() ? "ACTIVE" : "STOPPED"), 2, rows);
			Button stopButton = new Button("STOP");
			stopButton.setOnAction(new EventHandler<ActionEvent>() {
				@Override
				public void handle(ActionEvent e) {
					worker.stopWork();
					Platform.runLater(new Runnable() {
						@Override
						public void run() {
							updateWorkers();
						}
					});
				}
			});
			if (!worker.isActive()) {
				stopButton.setVisible(false);
			}
			grid.add(stopButton, 3, rows);
			rows++;
		}
	}

	private Label createHeadlineLabel(String text) {
		Label l = new Label(text);
		l.setFont(new Font("Arial", 16));
		return l;
	}
}
